package com.triplelink.builder.query.evalueter;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;

import com.triplelink.annotations.DatatypeProperty;
import com.triplelink.annotations.Property;
import com.triplelink.builder.query.QueryTL;
import com.triplelink.exception.TripleLinkException;

public class StringEvalueter
{
	@SuppressWarnings("unchecked")
	public static void putValue(Field field, Object currentEntity, String id, QueryTL resources) throws IllegalArgumentException, IllegalAccessException
	{
		field.setAccessible(true);
		
		Object value = field.get(currentEntity);
		
		if (value == null)
			return;
		
		Property property = field.getAnnotation(Property.class);
		DatatypeProperty datatypeProperty = field.getAnnotation(DatatypeProperty.class);
		
		if (value instanceof String)
		{
			resources.appendLiteral(id, property.uri(), (String) value, datatypeProperty);
		}
		else if (value instanceof Collection)
		{
			Type type = field.getGenericType();
			
			if (type instanceof ParameterizedType && ((ParameterizedType) type).getActualTypeArguments()[0] == String.class)
			{
				for (String obj : (Collection<String>) value)
					resources.appendLiteral(id, property.uri(), obj, datatypeProperty);
			}
			else
			{
				throw new TripleLinkException(getAcceptTypeMsgException(field, property));
			}
		}
		else if (value instanceof String[])
		{
			for (String obj : (String[]) value)
				resources.appendLiteral(id, property.uri(), obj, datatypeProperty);
		}
		else
		{
			throw new TripleLinkException(getAcceptTypeMsgException(field, property));
		}
	}
	
	private static String getAcceptTypeMsgException(Field field, Property property)
	{
		return field + ": the property " + property.uri() + " only acepets field of Type:"
				+ " String, Collection<String>, String[]";
	}
}